//
//  DebugNetWorkViewController.m
//  YK_DebugManager
//
//  Created by edward on 2021/1/14.
//

#import "DebugNetWorkViewController.h"
#import "DebugNetWorkManager.h"
#import "DebugNetWorkRecordDetailViewController.h"

@interface DebugNetWorkViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating>
///tableView
@property(nonatomic,strong) UITableView *tableView;

@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, strong) NSArray *searchResult;

@end

@implementation DebugNetWorkViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
}

- (void)setupUI
{
    self.title = @"请求日志";
    NSMutableDictionary *barTitleDic = [NSMutableDictionary dictionary];
    barTitleDic[NSForegroundColorAttributeName] = [UIColor blackColor];
    [self.navigationController.navigationBar setTitleTextAttributes:barTitleDic];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(closeViewController)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(clearDatas)];
    [self.view addSubview:self.tableView];
}
- (void)closeViewController
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)clearDatas
{
    [[DebugNetWorkManager sharedInstance] removeAllDatas];
    [self.tableView reloadData];
}
#pragma mark -tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchController.active) {
        return self.searchResult.count;
    }
    return [DebugNetWorkManager sharedInstance].records.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(UITableViewCell.class)];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:NSStringFromClass(UITableViewCell.class)];
        cell.backgroundColor = UIColor.clearColor;
        cell.contentView.backgroundColor = UIColor.clearColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    DebugNetWorkModel *record = [[DebugNetWorkModel alloc] init];
    if (self.searchController.active) {
        record = self.searchResult[indexPath.row];
    } else {
        record = [DebugNetWorkManager sharedInstance].records[indexPath.row];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@",record.url];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [format setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *time = @"";
    if ([record.startTime isKindOfClass:NSDate.class]) {
        time = [format stringFromDate:record.startTime];
    }else
    {
        time = [NSString stringWithFormat:@"%@",record.startTime];
    }
    cell.detailTextLabel.text = time;
    if (record.isException) {
        cell.textLabel.textColor = UIColor.redColor;
        cell.detailTextLabel.textColor = UIColor.redColor;
    }else
    {
        if (@available(iOS 13.0, *)) {
            cell.textLabel.textColor = UIColor.labelColor;
            cell.detailTextLabel.textColor = UIColor.labelColor;
        } else {
            cell.textLabel.textColor = UIColor.blackColor;
            cell.detailTextLabel.textColor = UIColor.blackColor;
        }
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugNetWorkModel *record = [[DebugNetWorkModel alloc] init];
    if (self.searchController.active) {
        record = self.searchResult[indexPath.row];
    } else {
        record = [DebugNetWorkManager sharedInstance].records[indexPath.row];
    }
    DebugNetWorkRecordDetailViewController *vc = [[DebugNetWorkRecordDetailViewController alloc] initWithRecord:record];
    
    if(self.searchController.active)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
#pragma mark -----------getter/setter------------
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, debug_top_Height, self.view.bounds.size.width, self.view.bounds.size.height - debug_top_Height - (self.view.safeAreaInsets.bottom)) style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 85;
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.backgroundColor = UIColor.clearColor;
        tableView.tableHeaderView = self.searchController.searchBar;
        _tableView = tableView;
    }
    return _tableView;
}
#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    NSString *inputStr = searchController.searchBar.text;
    NSMutableArray *arr = [NSMutableArray array];
    for (DebugNetWorkModel *record in [DebugNetWorkManager sharedInstance].records) {
        if ([[record.url lowercaseString] containsString:[inputStr lowercaseString]]) {
            //containsString（包含字符串）
            [arr addObject:record];
        }
    }
    self.searchResult = arr;
    [self.tableView reloadData];
}

- (UISearchController *)searchController
{
    if (!_searchController) {
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;
    }
    return _searchController;
}
- (NSArray *)searchResult
{
    if(!_searchResult)
    {
        _searchResult = [NSArray array];
    }
    return _searchResult;
}
- (void)dealloc
{
    
}
@end
